#!/usr/bin/perl
use strict;
use warnings;
use Carp;
use FindBin;
use Bio::SeqIO;
use List::Util qw/sum/;
use Bio::SearchIO;
use Getopt::Long;
use Math::Round qw(:all);
use Cwd;

 
 
 
&plot_tax($ARGV[0],$ARGV[1]);
sub plot_tax(){
my $num =10000;
         my $file = shift;
         my $name = shift;
     my %tax;
     open (FILE, "< $file")|| die ("Could not open fasta file $file!\n");
     while(<FILE>){
         my @line = split(/\t/,$_);
         my @des = split(/;/,$line[1]);
         my $kindom = "unknown";
         my $species = "unknown_species";
         foreach(@des){
             if ($_ =~ /^(.*)\{(.*)\}$/){
                 if ($2 eq "superkingdom"){
                     $kindom = $1;
                 }
                 if ($2 eq "kingdom"){
                     $kindom = $1;
                 }
                 if ($2 eq "species"){
                     $species = $1;
                 }
             }
         }
         if(exists $tax{$kindom}{$species}){
             $tax{$kindom}{$species}++;
         }else{
             $tax{$kindom}{$species}=1;
         }
     }
     my $un_matched=$num;
     my $other=0;
     my @key;
     my @values;
     
     foreach(keys %tax){
         my $kindom = $_;
         foreach (keys %{$tax{$_}}){
             my $species = $_;
             my $percent = nearest(.01, $tax{$kindom}{$species}/$num * 100);
             if($tax{$kindom}{$species}/$num >= 0.005){
                 push(@key,'"'.$kindom."-".$species.'"');
                 push(@values,$tax{$kindom}{$species});
				 $un_matched=$un_matched-$tax{$kindom}{$species};
             }else{
                 $other+=$tax{$kindom}{$species};
             }
            
         }
		
     }
	   $un_matched=$un_matched-$other;
	 
     my $r_out="";
     
     if(scalar(@key)>1){
         $r_out="pdf(file=\"$name.all_pie.pdf\",height=20,width=28)\n";
         $r_out.="slices<-c(".join(",",@values).",$other,$un_matched)\n";
         $r_out.="lbls<-c(".join(",",@key).",\"Other\",\"Unmatched\")\n";
         $r_out.="pct<-round(slices/sum(slices)*100,2)\n";
         $r_out.="lbls<-paste(lbls,pct)\n";
         $r_out.="lbls<-paste(lbls,\"%\",sep=\"\")\n";
         $r_out.="pie(slices,labels=lbls,col=rainbow(length(lbls)),main=\"Pie Chart of ALL\")\n";
         $r_out.="dev.off()\n";
         open R, "> $name.R" or die "Error:Cannot open file  Rfam/all.R : $! \n";     
           print R $r_out;
         close R;     
         process_cmd("R --no-save <  $name.R");
     }
     
     close FILE;
 }

 
 
 sub process_cmd {
     my ($cmd) = @_;
     print "CMD:\n$cmd\n"; 
     my $ret = system($cmd);
     if ($ret) {
         die "Error, cmd: $cmd died with ret ($ret) ";
     }
     return;
 }
